<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!taskDefKey || detailType == '1'">
    <!-- 档案借阅详情 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="detailType === '1' || editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="档案借阅信息"></title-name>
          <custom-form :formList="formList" :form="form" :editModel="editModel == 0 || archivesType !== '0' ? 'V' : ''">
          </custom-form>
        </a-card>
        <a-card v-if="archivesType !== '0' && (detailType !== '2' || form.results)" :bordered="false">
          <title-name title="利用效果"></title-name>
          <a-form-model-item prop="results" label="利用效果" class="requiredFormItem">
            <div v-if="archivesType === '1' && detailType !== '1'" style="margin-top: -3px">
              {{ form.results || '无' }}
            </div>
            <BaseTextarea v-else v-model="form.results" placeholder="请输入利用效果" />
          </a-form-model-item>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="!taskDefKey || detailType == '1'">
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="(editModel == 1 && (statusCode == '0' || statusCode == '3')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
          >{{ statusCode == '2' || statusCode == '3' ? '保存' : '保存草稿' }}</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="
            (editModel == 1 && (statusCode == '0' || statusCode == '3')) ||
            editModel == 2 ||
            (editModel != 0 && statusCode == '2') ||
            detailType === '1'
          "
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
          >提交</a-button
        >
        <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { archives } from '@/api/office/office/enterpriseHonorAndImgCollect' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import { createValidator, isPhone } from '@/utils/regExpression' // 正则校验
import { completeTask } from '@/api/process'

export default {
  name:'a'+Date.now(),
  extends: new BaseEditPage(),
  props: {
    detailType: [String, Number], // 详情类型：0 业务；1 审批；2 审批详情
  },
  data() {
    return {
      loading: { 0: false, 1: false }, // 草稿和提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {}, // 表单
      archivesType: '1', // 档案类型：0 申请；1 归还
      statusCode: '', // 审批状态
      rules: {
        content: [{ required: true, whitespace: true, message: '请输入借阅内容', trigger: 'change' }],
        objective: [{ required: true, whitespace: true, message: '请输入利用目的', trigger: 'change' }],
        phone: [{ required: true, validator: createValidator(isPhone, '请输入正确的手机号码', true), trigger: 'blur' }],
        backTime: [{ required: true, message: '请选择实际归还日期', trigger: 'change' }],
        planningBackTime: [{ required: true, message: '请选择计划归还日期', trigger: 'change' }],
        borrowingTime: [{ required: true, message: '请选择借阅日期', trigger: 'change' }],
        results: [{ required: true, whitespace: true, message: '请输入利用效果', trigger: 'change' }],
      }, // 校验规则
    }
  },
  mounted() {
    this.$route.meta.title = [
      this.detailType === '1' ? '归还已借阅档案' : '档案借阅查看',
      '档案借阅编辑',
      '档案借阅新增',
    ][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      archives
        .detail(this.id)
        .then((res) => {
          this.loading[0] = false
          this.form = res.data
          this.statusCode = res.data?.statusCode // 审批状态
        })
        .catch(() => {
          this.loading[0] = false
        })
    } else {
      const post = this.$currentPost()
      const user = this.$userInfo()
      // 初始化借阅日期
      this.$set(this.form, 'borrowingTime', this.$dateFormat(new Date(), 'D'))
      // 初始化单位
      this.$set(this.form, 'borrowingUnitName', (post.code === 'PD' ? post.orgName + '-' : '') + post.name)
      this.$set(this.form, 'borrowingUnitId', post.id)
      // 初始化用户信息
      this.$set(this.form, 'borrowingPersonName', user.name)
      this.$set(this.form, 'phone', user.employee.phoneNum)
    }
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'borrowingUnitName',
          type: 'BaseInput',
          disabled: true,
          label: '借阅单位',
        },
        {
          keyName: 'borrowingPersonName',
          type: 'BaseInput',
          disabled: true,
          label: '借阅人',
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          label: '联系电话',
        },
        {
          keyName: 'content',
          type: 'BaseInput',
          label: '借阅内容',
          span: 24,
        },
        {
          keyName: 'objective',
          type: 'BaseTextarea',
          label: '利用目的',
          span: 24,
          attrs: {
            maxLength: 500,
          },
        },
        {
          keyName: 'planningBackTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '计划归还日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return this.form.borrowingTime && current && current < this.moment(this.form.borrowingTime).startOf('day')
            },
          },
        },
        {
          keyName: 'borrowingTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '借阅日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return (
                (this.form.planningBackTime &&
                  current &&
                  current > this.moment(this.form.planningBackTime).endOf('day')) ||
                (this.form.backTime && current && current > this.moment(this.form.backTime).endOf('day'))
              )
            },
          },
        },
        {
          keyName: 'backTime',
          type: 'a-date-picker',
          hidden: this.archivesType === '0' || !this.form.backTime,
          placeholder: '请选择日期',
          label: '实际归还日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return this.form.borrowingTime && current && current < this.moment(this.form.borrowingTime).startOf('day')
            },
          },
        },
      ]
    },
  },
  methods: {
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e || statusCode === 0) {
          if (statusCode == '1' && that.detailType === '0') {
            that.$confirm({
              title: '温馨提示',
              content: '请确认是否要提交借阅申请，提交后不可修改',
              onOk: () => {
                // 提交表单
                return that.submitForm(statusCode)
              },
            })
          } else {
            that.submitForm(statusCode)
          }
        }
      })
    },
    async submitForm(statusCode) {
      let that = this
      let name = ['update', 'create'][that.editModel - 1] || 'update' // 根据操作切换url地址
      statusCode === 0 && that.$refs.ruleForm.clearValidate()
      // 提交表单
      let form = that.$clone(that.form)
      form.statusCode = (that.statusCode == '3' && statusCode == 0) || (that.statusCode == '2' && statusCode == 1) ? that.statusCode : statusCode
      if (statusCode == '1') {
        form.level = that.$currentPost().code
        form.orgId = that.$currentPost().deptId
      }
      that.loading[statusCode] = true
      let res = await archives[name](form)
        .then(() => {
          // 若detailType为0则为业务流程，否则为审批流程
          if (that.detailType === '0') {
            that.loading[statusCode] = false
            that.$message.success(['保存', '提交'][statusCode] + '成功！')
            that.$multiTab.close()
          } else {
            return 'audit'
          }
        })
        .catch(() => {
          // that.$message.warning(['保存', '提交'][statusCode] + '失败！')
          that.loading[statusCode] = false
        })
      if (res === 'audit') {
        const data = {
          procInstId: that.procInstId,
          taskId: that.taskId,
          userId: that.$userInfo().id,
        }
        // 结束流程
        return completeTask(data)
          .then((res) => {
            that.loading[statusCode] = false
            if (res.status === 200) {
              window.opener.postMessage('finish', window.location.origin)
              // that.$success({
              //   content: '审批提交成功，即将自动关闭当前窗口',
              //   onOk() {
                  window.close()
              //   },
              // })
              // setTimeout(() => {
              //   window.close()
              // }, 2000)
            } else {
              that.$error({ content: '提交失败，请稍后重试' })
            }
          })
          .catch(() => {
            that.loading[statusCode] = false
          })
      } else {
        return res
      }
    },
  },
}
</script>